package org.raymond.iworks.study.basic.structure.stack;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
public class SingleLinkedListStack {
    private int max;
    private StackNode top;

    /**
     * stack: top->(top-1)->(top-2)...(max)
     */
    public SingleLinkedListStack(int max){
        this.max = max;
    }

    public void push(int i){
        if(isFull()){
            System.err.println("链表栈已满");
            return;
        }
        StackNode node = new StackNode(i);
        if(top==null){
            top = node;
            return;
        }
        StackNode cur = top;
        while(true){
            if(cur.next==null){
                break;
            }
            cur = cur.next;
        }
        cur.next=node;
    }

    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("链表栈已空");
        }
        int val = top.val;
        top = top.next;
        return val;
    }

    public boolean isFull(){
        return size()==max;
    }
    public boolean isEmpty(){
        return top==null || size()==0;
    }
    public int size(){
        StackNode cur = top;
        int count = 0;
        while(cur!=null){
            cur = cur.next;
            count++;
        }
        return count;
    }

    public void show(){
        if(isEmpty()){
            System.err.println("链表栈已空");
            return;
        }
        StackNode cur = top;
        System.out.printf("栈节点: %s\n", cur);
        while(true){
            if(cur.next==null){
                break;
            }
            cur = cur.next;
            System.out.printf("栈节点: %s\n", cur);
        }
    }
}
